package cn.wolfcode.mq;

import cn.wolfcode.service.IOrderInfoService;
import cn.wolfcode.web.msg.SeckillCodeMsg;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@RocketMQMessageListener(
        consumerGroup = "MQOrderListener",
        topic = MQConstant.ORDER_PEDDING_TOPIC
)
public class MQOrderListener  implements RocketMQListener<OrderMessage> {

    @Autowired
    private IOrderInfoService orderInfoService;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;


    @Override
    public void onMessage(OrderMessage orderMessage) {
        log.info("进入到了订单的消费者");
        Integer time = orderMessage.getTime();
        String token = orderMessage.getToken();
        Long seckillId = orderMessage.getSeckillId();
        Long userPhone = orderMessage.getUserPhone();
        OrderMQResult orderMQResult = new OrderMQResult();
        orderMQResult.setToken(token);
        orderMQResult.setTime(time);
        orderMQResult.setSeckillId(seckillId);

        String tag="";


        //贴标签 成功还是失败
        try {
            String order = orderInfoService.doSeckill(seckillId, time, userPhone);
            log.info("订单编号是"+order);
//            System.out.println(order);
            orderMQResult.setOrderNo(order);
            tag=MQConstant.ORDER_RESULT_SUCCESS_TAG;
            MessageBuilder<OrderMQResult> messageBuilder = MessageBuilder.withPayload(orderMQResult);
            rocketMQTemplate.syncSend(MQConstant.ORDER_PAY_TIMEOUT_TOPIC,messageBuilder.build(),5000,10);


        }catch (Exception e){
            e.printStackTrace();
            orderMQResult.setCode(SeckillCodeMsg.SECKILL_ERROR.getCode());
            orderMQResult.setMsg(SeckillCodeMsg.SECKILL_ERROR.getMsg());
            tag=MQConstant.ORDER_RESULT_FAIL_TAG;
        }

        //往另一个队列里面发消息
        rocketMQTemplate.sendOneWay(MQConstant.ORDER_RESULT_TOPIC+":"+tag,orderMQResult);



    }
}
